// pages/home/home.js
import * as socketUtil from '../../api/socketUtil'
import * as API_Classify from '../../api/classify'
import * as API_Store from '../../api/store'
import * as API_Product from '../../api/product'
const config = require('../../utils/config.js')
const service = require('../../utils/service')
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min')
const citySelector = requirePlugin('citySelector');
var qqMapSdk;
function param(longitude, latitude, newUseFlag, pageNum, pageSize, classifyId, load, finished, cityCode) {
  this.longitude = longitude
  this.latitude = latitude
  this.newUseFlag = newUseFlag
  this.pageNum = pageNum
  this.pageSize = pageSize
  this.classifyId = classifyId
  this.load = load
  this.finished = finished
  this.cityCode = cityCode
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cityList: ['北京市', '上海市', '天津市', '重庆市'],
    //四种分类
    //固定写死
    one: {},
    two: {},
    thr: {},
    fourth: {},
    paramsArray: [],
    cityCode: '',
    //定位
    latitude: '',
    longitude: '',
    params: {
      //经度
      longitude: '',
      //纬度
      latitude: '',
      newUseFlag: 'Y',
      pageNum: 1,
      pageSize: 10,
      cityCode: ''
    },
    //新客专享
    newProductList: [],
    fixedState: false,
    SelectTopViewHeight: 0,
    pageHeight: 0,
    headshow: 1,
    //classHeadshow:0,
    tab_index: 0,
    tabSwiperHeight: 0,
    serviceClassify: [
      { id: 0, classifyName: '全部' },
    ],
    agentsListArry: [],
    locationAddr: '',
    locationFail: false,//定位失败标识
    starList: [, , , , ,],
    section2List: [],
    storeId: null,
    storeAddress: '',
    storeBanner: [],
    vipPrice: 0
  },
  getClassList () {
    getApp().https.ajax({
      method: 'get',
      url: '/storeClassify/second'
    }).then(({ data }) => {
      const arr = []
      data.forEach(item => {
        if(item.showWechat == 'Y') {
          arr.push(item)
        }
      })

      this.setData({
        section2List: arr
      })
    })
  },
  getIndex (latitude, longitude) {
    let data = {}
    if (getApp().globalData.selectStoreId === 0) {
      data = {
        longitude: longitude,
        latitude: latitude
      }
    } else {
      data = {
        selectStoreId: getApp().globalData.selectStoreId
      }
    }
    getApp().https.ajax({
      method: 'post',
      url: '/store/recentlyStore',
      data: data
    }).then(({ data }) => {
      getApp().globalData.selectStoreId = data.id
      this.setData({
        storeId: data.id,
        storeAddress: data.storeName,
        storeBanner: data.bannerList,
        storeShowImage: data.storeShowImage ? data.storeShowImage.split(',') : data.storeShowImage,
        vipPrice: data.vipPrice
      })
    })
  },
  goProductDetail(e) {
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?id=' + e.currentTarget.dataset.id,
    })
  },
  RECEIVE_MSG_INFORM: function (json) {
    //收到新消息
    let reqParam = {};
    socketUtil.sendData("MY_MSG_UNREAD_COUNT", reqParam);
  },
  MY_MSG_UNREAD_COUNT: function (json) {
    let unreadMsgCount = json.info.unreadMsgCount;
    if (unreadMsgCount == 0) {
      wx.removeTabBarBadge({
        index: 1
      })
    } else {
      wx.setTabBarBadge({
        index: 1,
        text: unreadMsgCount + ''
      })
    }
  },
  onPageScroll: function (e) {
    let opacity = 0;
    if (e.scrollTop > 100) {
      opacity = 0;
    } else {
      opacity = 1;
    }

    // opacity = (100- (e.scrollTop/2))/100
    this.setData({
      headshow: opacity
    })
    let statusBarHeightpx = this.data.statusBarHeightpx;
    let tofixedStateHeight = this.data.SelectTopViewHeight - statusBarHeightpx - 40 - 5;

    // console.info("statusBarHeightpx"+statusBarHeightpx);
    // console.info("tofixedStateHeight"+tofixedStateHeight);
    // console.info("e.scrollTop"+e.scrollTop);
    if (e.scrollTop > tofixedStateHeight) {
      //滑动到下面的数据，需要浮动
      this.setData({
        fixedState: true
      })
    } else {
      this.setData({
        fixedState: false
      })
    }
  },
  goSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  //通过分类进入列表
  goProductList(e) {
    wx.navigateTo({
      url: '../productList/productList?classifyId=' + e.currentTarget.dataset.id,
    })
  },
  //
  goAllClassify() {
    wx.navigateTo({
      url: '/pages/classify/classify',
    })
  },
  goMore() {
    let code = this.data.params.cityCode
    wx.navigateTo({
      url: '../productLineList/productLineList?cityCode=' + code,
    })
  },
  switchTab: function (e) {

    let current = e.currentTarget.dataset.tab_index;
    //此处setData会触发tabIndexChange，所以不用主动调用tabIndexChangeHandle，避免多次执行
    this.setData({ tab_index: current, scrollhandle: false });

  },
  tabIndexChange: function (e) {
    console.info('tabIndexChange')
    let current = e.detail.current;
    this.tabIndexChangeHandle(current);
    this.setData({ scrollhandle: true })
    //this.reCal();
  },
  tabIndexChangeHandle: function (current) {
    console.info('tabIndexChangeHandle')
    this.setData({ tab_index: current });
    console.info('页签变化为' + current)
    if (this.data.scrollhandle) {
      //手动滑动才需要滑动到对应位置
      wx.createSelectorQuery()
        .select('.select_tab_view')
        .node()
        .exec((res) => {
          const scrollView = res[0].node;
          scrollView.scrollIntoView(".act")
        })
    }
    let item = this.data.paramsArray[current]
    if (item.load) {
      this.getProductList()
    }

  },
  nextSwiper: function () {
    let len = this.data.serviceClassify.length;
    let current = this.data.tab_index;
    let next = current + 1;
    if (next > len - 1) {
      next = 0;
    }
    this.tabIndexChangeHandle(next);
  },
  /**
  showRightRecal:function(){
    //手动滑动才需要滑动到对应位置
    let that=this;
    wx.createSelectorQuery()
    .selectAll('.item')
    .boundingClientRect(function (rect) {
      let len= rect.length;
      if(len>0){
        //有元素
        let lastItem= rect[len-1];
        let right= Number(lastItem.right);
        if(right>getApp().globalData.clientWidth){
          that.setData({classHeadshow:1});
        }
      }
    }).exec();
  },
  
   reCal:function(){
    
    let query = wx.createSelectorQuery();
    query.select('#swiperitem'+this.data.tab_index).boundingClientRect(rect=>{
      
      let clientHeight = rect.height;
      let clientWidth = rect.width;
      let ratio = 750 / clientWidth;
      let height = clientHeight * ratio;
      if(height>this.data.tabSwiperHeight){
        this.setData({tabSwiperHeight:height})
      }
     
    }).exec();
  },*/
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let globalData = getApp().globalData;
    // let statusBarHeight=globalData.systemInfo.statusBarHeight;
    // let statusBarHeightpx = globalData.statusBarHeightpx;
    // let pageHeight = globalData.systemInfo.windowHeight - statusBarHeightpx - 40;
    // this.setData({ statusBarHeightpx: statusBarHeightpx, pageHeight: pageHeight });
    //加载分类数据
    // this.loadIndexData()
    //定位信息
    this.initLocation()
    this.getClassList()
    //滑块数据
  },
  initSlider() {
    let lat = this.data.latitude
    let lng = this.data.longitude
    API_Classify.getFirstList().then(res => {
      let arr = this.data.serviceClassify
      arr.push(...res.data)
      let resArr = []
      for (var i = 0; i < arr.length; i++) {
        resArr.push([])
      }
      let paramArr = []
      this.setData({
        serviceClassify: arr,
        agentsListArry: resArr
      })
      let sArr = this.data.serviceClassify
      let cityCode = this.data.cityCode
      for (var i = 0; i < sArr.length; i++) {
        paramArr.push(new param(
          lng,
          lat,
          'Y',
          1,
          20,
          sArr[i].id,
          true,
          false,
          cityCode
        ))
      }
      this.setData({ paramsArray: paramArr })
      this.getProductList()

    })
  },
  goStore(e) {
    wx.navigateTo({
      url: '/pages/storeHome/storeHome?id=' + e.currentTarget.dataset.id,
    })
  },
  //加载首页数据
  getProductList() {
    let index = this.data.tab_index
    API_Store.getList(this.data.paramsArray[index]).then(res => {
      let arr = this.data.agentsListArry
      for (let item of res.data.rows) {
        item.storeLevel = item.storeLevel.toFixed(1)
      }
      arr[index].push(...res.data.rows)
      let paramArr = this.data.paramsArray
      paramArr[index].load = false
      paramArr[index].finished = res.data.lastPage
      this.setData({
        agentsListArry: arr,
        paramsArray: paramArr
      })
    })
  },
  loadIndexData() {
    API_Classify.customerList().then(res => {
      let data = res.data
      for (var i = 0; i < data.length; i++) {
        if (1 == data[i].id) {
          data[i].child = data[i].child.slice(0, 3)
          this.setData({ one: data[i] })
        }
        if (2 == data[i].id) {
          data[i].child = data[i].child.slice(0, 2)
          this.setData({ two: data[i] })
        }
        if (3 == data[i].id) {
          data[i].child = data[i].child.slice(0, 2)
          this.setData({ thr: data[i] })
        }
        if (4 == data[i].id) {
          data[i].child = data[i].child.slice(0, 3)
          this.setData({ fourth: data[i] })
        }
      }
    })
  },
  initNewUserProduct() {
    API_Product.getList(this.data.params).then(res => {
      let arr = []
      arr.push(...res.data.rows)
      this.setData({ newProductList: arr })
      this.reCalSelectTopViewHeight();
    })
  },
  getCurrentLocation () {
    wx.showLoading()
    let that = this
    wx.getLocation({
      type: 'gcj02',
      // //开启高精准度
      // isHighAccuracy:true,
      // //最多五秒等待
      // highAccuracyExpireTime:5000,
      success: function (res) {
        wx.hideLoading()
        //纬度
        var latitude = res.latitude
        getApp().globalData.latitude = latitude
        //经度
        var longitude = res.longitude
        getApp().globalData.longitude = longitude
        that.getIndex(latitude, longitude)
        // that.reverseLocation(latitude, longitude)
        that.data.locationFail = false;

      },
      fail(res) {
        wx.hideLoading()
        if (res.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' ||
        res.errMsg === 'getLocation:fail system permission denied' ||
        res.errMsg === 'getLocation:fail:system permission denied') {
          wx.showModal({
            title: '您未开启地理位置授权',
            content: '请在系统设置中打开位置授权，然后下拉刷新页面',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          wx.showToast({
            title: '定位获取失败！',
            icon: 'none'
          })
        }
        // that.data.locationFail = true;
        // that.localFail();
      }
    })
  },
  async initLocation() {
    wx.showLoading();
    wx.getSetting({
      success: (res) => {
        let authSetting = res.authSetting
        if (authSetting['scope.userLocation']) {
          this.getCurrentLocation()
        } else if (authSetting['scope.userLocation'] === false) {
          wx.hideLoading()
          wx.showModal({
            title: '您未开启地理位置授权',
            content: '请在系统设置中打开位置授权，然后下拉刷新页面',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getCurrentLocation()
            },
            fail: () => {
              wx.hideLoading()
              wx.showModal({
                title: '您未开启地理位置授权',
                content: '请在系统设置中打开位置授权，然后下拉刷新页面',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        }
      },
      fail: () => {
        wx.hideLoading()
      }
    })
  },
  reverseLocation(latitude, longitude, showName) {
    let that = this
    qqMapSdk = new QQMapWX({
      key: config.QQMapKey
    });
    qqMapSdk.reverseGeocoder({
      location: { latitude: latitude, longitude: longitude },
      complete(res) {
        if (!res.status && res.status == 0) {
          console.log(res);
          that.data.locationFail = false;
          let address_reference = res.result.address_reference;
          let locationAddr = res.result.address;
          if (address_reference) {
            let landmark_l2 = address_reference.landmark_l2;
            if (landmark_l2) {
              locationAddr = landmark_l2.title;
            }
            let landmark_l1 = address_reference.landmark_l1;
            if (landmark_l1) {
              locationAddr = landmark_l1.title;
            }
          }
          if (showName) {
            locationAddr = showName;
          }
          const { ad_info } = res.result
          let provinceCode = ad_info.adcode.substr(0, 2) + '0000'
          that.setData({
            latitude: latitude,
            longitude: longitude,
            'params.longitude': longitude,
            'params.latitude': latitude,
            locationAddr: locationAddr,
            serviceClassify: [{ id: 0, classifyName: '全部' }],
          })
          console.log(res.result)
          if (that.data.cityList.includes(ad_info.city)) {
            let cityCode = ad_info.adcode.substr(0, 2) + '0000'
            that.setData({
              cityCode: cityCode,
              'params.cityCode': cityCode,
            })
            getApp().globalData.cityCode = cityCode

          } else {
            let cityCode = ad_info.adcode.substr(0, 4) + '00'
            that.setData({
              cityCode: cityCode,
              'params.cityCode': cityCode,
            })
            getApp().globalData.cityCode = cityCode
          }
          that.initSlider()
          that.initNewUserProduct()
        } else {
          wx.showToast({
            title: '地理位置获取失败！',
            icon: 'none'
          })
          // that.data.locationFail = true;
          // that.localFail();
        }
      }
    })
  },
  localFail() {
    const key = config.QQMapKey; // 使用在腾讯位置服务申请的key
    const referer = '一起飒'; // 调用插件的app的名称
    const hotCitys = ''; // 用户自定义的的热门城市
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
    })
  },
  changeLocation() {
    let that = this
    wx.chooseLocation({
      success: (res) => {
        // that.localSuccess();

        let addName = "";
        if (res.name) {
          addName = res.name;
        } else {
          addName = res.address;
        }
        if (addName == "") {
          that.initLocation()
        } else {
          this.setData({
            locationAddr: addName,
            latitude: res.latitude,
            longitude: res.longitude
          })
          //纬度
          var latitude = res.latitude
          getApp().globalData.latitude = latitude
          //经度
          var longitude = res.longitude
          getApp().globalData.longitude = longitude
          that.reverseLocation(latitude, longitude, addName)
        }
      },
      complete(res) {
        console.log(res)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().watch(this.MY_MSG_UNREAD_COUNT, 'MY_MSG_UNREAD_COUNT')//注册监听
    getApp().watch(this.RECEIVE_MSG_INFORM, 'RECEIVE_MSG_INFORM')//注册监听
    let reqParam = {};
    socketUtil.sendData("MY_MSG_UNREAD_COUNT", reqParam);
    //this.showRightRecal();

    // if (this.data.locationFail) {
    //   this.doLocal()

    // }
    // this.doLocal()
    if (getApp().globalData.selectStoreId !== 0) {
      this.getIndex()
    }
  },

  reCalSelectTopViewHeight: function () {
    let that = this;
    wx.createSelectorQuery()
      .selectAll('.selectTopView')
      .boundingClientRect(function (rect) {
        let len = rect.length;

        if (len > 0) {
          //有元素
          let lastItem = rect[0];
          let top = Number(lastItem.top);
          that.setData({ SelectTopViewHeight: top });
        }
      }).exec();
  },
  doLocal() {
    if (this.data.locationFail) {
      //自动定位失败则手动选择城市
      const selectedCity = citySelector.getCity(); // 选择城市后返回城市信息对象，若未选择返回null
      if (null != selectedCity) {
        //返回了选择的城市
        let location = selectedCity.location;
        let latitude = location.latitude;
        let longitude = location.longitude;
        this.reverseLocation(latitude, longitude)
      }
      if (!this.data.latitude && null == selectedCity) {
        //没有定位信息且程序是空的则继续
        this.initLocation()
      }
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initLocation()
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let index = this.data.tab_index
    // let itemArr = this.data.paramsArray
    // if (!itemArr[index].finished) {
    //   itemArr[index].pageNum = itemArr[index].pageNum + 1
    //   this.setData({ paramsArray: itemArr })
    //   this.getProductList()
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})